package com.scsystem.xysc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scsystem.xysc.mapper.OrderMapper;
import com.scsystem.xysc.mapper.UserMapper;
import com.scsystem.xysc.pojo.Order;
import com.scsystem.xysc.pojo.Product;
import com.scsystem.xysc.pojo.User;
import com.scsystem.xysc.pojo.vo.ReturnResult;
import com.scsystem.xysc.service.ProductService;
import com.scsystem.xysc.mapper.ProductMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
* @author sky
* @description 针对表【product】的数据库操作Service实现
* @createDate 2023-10-15 22:55:23
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public ReturnResult<Boolean> purchase(Long pid, Integer quantity, Long uid) {
        Product product = productMapper.selectById(pid);
        if (product != null && product.getStockQuantity() >= quantity) {
            // 创建订单
            User user = userMapper.selectById(uid);
            if (user != null) {
                Order order = new Order();
                order.setUserId(uid);
                order.setProductId(product.getProductId());
                order.setQuantity(quantity);
                order.setAddress(user.getAddress());
                order.setPhoneNumber(user.getPhoneNumber());
                order.setProductPrice((product.getPrice().multiply(new BigDecimal(quantity))));
                order.setStatus("待付款");
                order.setCreateDate(LocalDateTime.now());
                orderMapper.insert(order);
            }else {
                return new ReturnResult<>(400, "用户不存在", false);
            }
            // 减库存
            product.setStockQuantity(product.getStockQuantity() - quantity);
            productMapper.updateById(product);
            return new ReturnResult<>(200, "购买成功", true);
        }else {
            return new ReturnResult<>(400, "库存不足或商品不存在", false);
        }
    }
}




